new Vue({
    el: '#app',
    data: {
        coupons: [],
        activeFilter: 'all',
        userAvatarUrl: 'https://randomuser.me/api/portraits/men/32.jpg',
        username: '用户昵称',
        loading: true,
        menuOpen: false
    },
    computed: {
        filteredCoupons() {
            if (this.activeFilter === 'all') {
                return this.coupons;
            } else {
                return this.coupons.filter(coupon => coupon.status === this.activeFilter);
            }
        }
    },
    created() {
        this.fetchUserInfo();
        this.fetchCoupons();
    },
    methods: {
        toggleMenu() {
            this.menuOpen = !this.menuOpen;
        },

        fetchUserInfo() {
            // 模拟用户信息获取
            setTimeout(() => {
                this.username = '购物达人';
                this.userAvatarUrl = 'https://randomuser.me/api/portraits/men/32.jpg';
            }, 300);
        },

        fetchCoupons() {
            // 模拟API请求
            //获取所有优惠券信息
            var settings = {
                "url": "http://localhost:8080/activity/findAllCoupons",
                "method": "GET",
                "timeout": 0,
                "headers": {
                    "token": localStorage.getItem('token'),
                    "Accept": "*/*",
                },
            };
            $.ajax(settings).done((response) => {
                this.coupons = response.data;
                this.loading = false;
            });
            //h获取用户拥有的优惠卷
            $.ajax({
                url: 'http://localhost:8080/activity/findCouponByUserId',
                type: 'Get',
                data: { userId: localStorage.getItem('userId') },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (response) => {
                    console.log(this.coupons);   
                    const userCoupons = new Set(response.data.map(coupon => coupon.couponId));
                    this.coupons = this.coupons.map(coupon => ({
                        ...coupon,
                        status: userCoupons.has(coupon.couponId) ? 'claimed' : (new Date() > new Date(coupon.couponEndTime) ? 'expired' : 'available')

                    }))
                    console.log(this.coupons);

                }
            })
        },
        //用户领取优惠券
        

        filterCoupons(filter) {
            this.activeFilter = filter;
        },

        claimCoupon(coupon) {
            if (coupon.status !== 'available') return;

            // 模拟API请求
            this.loading = true;
            $.ajax({
                url: 'http://localhost:8080/activity/addUserCoupon',
                type: 'POST',
                data:{
                    userId: localStorage.getItem('userId'),
                    couponId: coupon.couponId
                },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (response) => {
                    this.loading = false;
                    if (response.code === 200) {
                        alert('领取成功！，请在我的优惠券查看');
                        this.fetchCoupons();
                    }
                },
                error: (error) => { 
                    this.loading = false;
                    alert('网络错误，领取失败');
                }
            })
        },

        formatDate(dateString) {
            if (!dateString) return '无限制';
            return dateString.split(' ')[0];
        },

        handleUserClick() {
            if (this.username === '请登录') {
                window.location.href = '/login.html';
            }
        },

        logout() {
            // 实现登出逻辑
            this.username = '请登录';
            alert('您已成功退出登录');
        },
         fetchUserInfo() {
            const token = localStorage.getItem('token') || ''; // 从本地存储获取token
            if (!token) {
                console.warn('未找到用户token，无法加载用户信息。');
                this.userAvatarUrl = '/photo/Profile picture/微信图片_20240927140746.jpg';
                this.username = '请登录';
                return;
            }

            $.ajax({
                url: 'http://localhost:8080/user/findUserById',
                type: 'Post',
                dataType: 'json',
                headers: {
                    'token': token
                },
                data: {
                    userId: localStorage.getItem('userId') || ''
                },
                success: (response) => {
                    if (response.code === 200) {
                        this.username = response.data.userName;
                        this.userAvatarUrl = 'http://localhost:8080' + response.data.avatar;
                        console.log(this.username);
                        console.log(this.userAvatarUrl);

                        // 检查是否为新用户
                        // this.checkNewUser();
                    }
                },
                error: function (xhr, status, error) {
                    console.error('加载用户信息失败:', error, xhr.responseText);
                    if (xhr.status === 401) {
                        // token过期或无效
                        logout(); // 调用 logout 函数清除存储并跳转
                    } else {
                        alert('加载用户信息失败，请稍后重试');
                    }
                }
            });
        },
    }
});